package postgres

import (
	"auth/model"
	"auth/model/entity"
)

var Resource = &resource{}

type resource struct{}

func (a *resource) Create(m *entity.Resource) (int64, error) {
	err := db.Create(m).Error
	return m.ID, err
}

func (a *resource) Find(id int64) (*entity.Resource, error) {
	e := &entity.Resource{}
	err := db.Model(&entity.Resource{}).First(&e, id).Error
	return e, err
}

func (a *resource) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.Resource{}).Where("id = ?", id).Updates(dict).Error
}

func (a *resource) Delete(id int64) error {
	return db.Delete(&entity.Resource{}, id).Error
}

func (a *resource) List(in *model.ResourceListRequest) (int, []*entity.Resource, error) {
	var (
		q         = db.Model(&entity.Resource{})
		err       error
		total     int64
		resources []*entity.Resource
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&resources).Error; err != nil {
		return 0, nil, err
	}
	return int(total), resources, nil
}

func (a *resource) FindByParameterCount(parameter *model.ResourceByParameterRequest) (int64, error) {
	var (
		q   = db.Model(&entity.Resource{})
		err error
		//out     entity.Resource
		count int64
	)

	err = q.Where("name = ? or resource =?", parameter.Name, parameter.Resource).Count(&count).Error
	return count, err
}
